import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;

import javax.swing.JPanel;


public class VideoPlayer extends JPanel implements Runnable, IStreamSync {
	//private BufferedImage[] buffer1;
	//private BufferedImage[] buffer2;

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private VideoFile videoFile;
	private VideoFrame videoBuffer;
    private boolean playing = true;
	BufferedImage img;
	
	//private Object lockPlay = new Object();  //lock for playing
	//private Object lockTime = new Object();  //lock for time stamp
    
    @Override
	public void paint(Graphics g) {
		g.drawImage(img, 0, 0, null);
	}    
    
    public void setPercentage(float p){
    	long frameIdx = (long) (videoFile.getTotalFrameNumber()*p);
    	//synchronized (lockTime) {
    	//pause();
    		videoFile.setFramePosition(frameIdx);
    		videoFile.readNextFrame(videoBuffer);
    		//start();
		//}
    }
    
	public VideoPlayer(String fileName){
		
		videoFile = new VideoFile(fileName);
		int width = videoFile.getWidth();
		int height = videoFile.getHeight();

		videoBuffer = new VideoFrame(0, new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB));
		img = videoBuffer.image;
		
		this.setPreferredSize(new Dimension(width, height));
	}
	
	public double getFPS(){
		return videoFile.getFps();
	}
	
	public void displayNextFrame(){
		videoFile.readNextFrame(videoBuffer);
		repaint();
	}

	@Override
	public void run() {
		while(true){
			if(playing){
				//synchronized(lockTime){
					displayNextFrame();
				//}
			}
		}
	}

	@Override
	public void start() {
		// TODO Auto-generated method stub
		//synchronized(lockPlay){
			playing = true;
		//}
	}

	@Override
	public void pause() {
		// TODO Auto-generated method stub
		//synchronized(lockPlay){
			playing = false;
		//}
	}

	@Override
	public void stop() {
		// TODO Auto-generated method stub
		//synchronized(lockPlay){
			playing = false;
		//}
	}

	@Override
	public long getCurrentTimeStamp() {
		// TODO Auto-generated method stub
		return videoBuffer.timeStamp;
	}
	
	
}
